import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo, login } from '@/api/user'
import { resetRouter, constantRoutes } from '@/router'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 静态路由的数组
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  loginOut(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, newInfo) {
    state.userInfo = newInfo
  },
  setRoutes(state, newroutes) {
    state.routes = [...constantRoutes, ...newroutes]
  }
}
// 登录表单校验  调用登录接口 存储token并缓存
const actions = {
  async login(context, data) {
    console.log(data)
    const token = await login(data)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },
  exitLogin(context) {
    context.commit('loginOut')
    context.commit('setUserInfo', {})
    resetRouter() // 退出之后重置路由信息
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
